package net.obxlabs.tweetpad.behaviour;

import net.nexttext.*;
import net.nexttext.behaviour.*;
import net.nexttext.property.*;

public class Gate extends AbstractAction {
	private String key;
	private Action thruAction;
	private boolean checkParents;
	
	public Gate(String propName, Action action) {
		this(propName, action, false);
	}
	
	public Gate(String propName, Action action, boolean checkAll) {
		key = propName;
		thruAction = action;
		checkParents = checkAll;
	}
	
	public ActionResult behave(TextObject to) {
		if (hasKey(to)) {
			return thruAction.behave(to);
		}
		
		if (checkParents) {
			// go up the tree, looking for a key
			for (TextObjectGroup parent = to.getParent(); parent != null; parent = parent.getParent()) {
				if (hasKey(parent)) {
					return thruAction.behave(to);
				}
			}
		}
		
		return new ActionResult(false, false, false);
	}
	
	private boolean hasKey(TextObject to) {
		BooleanProperty toKey = (BooleanProperty)to.getProperty(key);
		if (toKey != null) {
			if (toKey.get()) {
				// the key has been set and is true, go through
				return true;
			}
		}
		return false;
	}
}
